package com.yima.baseproj.config.validate;

import com.yima.baseproj.config.exception.type.ParamException;
import com.yima.baseproj.module.config.utils.ResultCodeE;
import com.yima.baseproj.module.config.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

/**
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Slf4j
@RestControllerAdvice
public class ValidationInterceptor extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String message = getErrorOne(ex.getBindingResult().getAllErrors());
        return new ResponseEntity<Object>(ParamException.getInstance(message),HttpStatus.OK);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<Object>(ParamException.getInstance(getErrorOne(ex.getBindingResult().getAllErrors())),HttpStatus.OK);
    }

    private Object getError(List<ObjectError> allErrors) {
        StringBuffer message = new StringBuffer();
        for(ObjectError error: allErrors){
            message.append(error.getDefaultMessage()).append(" & ");
        }
        log.error(message.substring(0, message.length() - 3));  // 因为&两边空格
        return ResultUtil.error(ResultCodeE.PARAMETER_FAIL.getCode(),message.substring(0, message.length() - 3));
    }

    /**
     * 获取第一个错误信息
     * @param allErrors
     * @return
     */
    private String getErrorOne(List<ObjectError> allErrors) {
        String message = allErrors.get(0).getDefaultMessage();
        log.error(message);
        if(message.startsWith("Failed to convert property")){
            return "数据类型错误";
        }
        return message;
    }
}
